<?php

namespace App\V3\V3_2_7\Controllers;

use App\Http\Controllers\Controller;
use App\Services\CommonService;
use App\V3\V3_2_7\Services\SellReportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SellReportController extends BaseController
{
    /**
     * 根据物料名，统计销售报表
     */
    public function materielNameList(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'pageSize'      => 'required|integer|min:1',//页面大小
            'currentPage'   => 'required|integer|min:1',//当前页
            'start_time'    => 'date_format:Y-m-d',//开始时间
            'end_time'      => 'date_format:Y-m-d',//开始时间
            'materiel_name' => 'string|between:1,100',//物料名称
            'sell_price_sort'   => 'nullable|string|in:asc,ASC,desc,DESC',//销售价格排序，asc升，desc降，默认空
            'sell_profit_sort'  => 'nullable|string|in:asc,ASC,desc,DESC',//销售利润排序，asc升，desc降，默认空
        ],[
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer'  => '参数`pageSize`仅能为数字',
            'pageSize.min'      => '页面展示数据最小为“1”条',
            'currentPage.required'  => '参数`currentPage`丢失',
            'currentPage.integer'   => '参数`currentPage`仅能为数字',
            'currentPage.min'       => '当前分页最小为第“1”页',
        ]);

        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }
        $mainId = 0;
        if($this->getUserId() == $this->getMainUserId()) {
            //调用查询接口
            $mainId = $this->getMainUserId();
        } else {
            if($this->isShareStorage()) {
                //调用查询接口
                $mainId = $this->getMainUserId();
            } else {
                $data['user_id'] = $this->getUserId();
            }
        }

        return SellReportService::materielNameList($mainId, $data);
    }

    /**
     * 根据物料信息查询销售报表（二级）
     */
    public function sellGoodsStatementList(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'sell_id' => 'required|integer|min:1',//商品id
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
        ], [
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'pageSize.min' => '页面展示数据最小为“1”条',
            'currentPage.required' => '参数`currentPage`丢失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
            'currentPage.min' => '当前分页最小为第“1”页',
            'sell_id.required' => '参数`sell_id`丢失',
            'sell_id.integer' => '参数`sell_id`仅能为数字',
        ]);

        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }
        //调用查询接口
        $mainId = $this->getMainUserId();
        return SellReportService::sellGoodsStatementList($mainId, $data);
    }

    /**
     * 根据物料信息查询销售报表（二级）
     */
    public function sellGoodsStatement(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'goods_id'      => 'required|integer|min:1',//商品id
            'pageSize'      => 'required|integer|min:1',//页面大小
            'currentPage'   => 'required|integer|min:1',//当前页
            'start_time'    => 'date_format:Y-m-d',//开始时间
            'end_time'      => 'date_format:Y-m-d',//开始时间
            'sell_num_sort'   => 'nullable|string|in:asc,ASC,desc,DESC',//销售数量排序，asc升，desc降，默认空
            'sell_debt_sort'   => 'nullable|string|in:asc,ASC,desc,DESC',//销售数量排序，asc升，desc降，默认空
            'type' => [
                'required',
                Rule::In([2, 6]),
            ],//条码类型0:商品;1:套餐;
        ],[
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer'  => '参数`pageSize`仅能为数字',
            'pageSize.min'      => '页面展示数据最小为“1”条',
            'currentPage.required'  => '参数`currentPage`丢失',
            'currentPage.integer'   => '参数`currentPage`仅能为数字',
            'currentPage.min'       => '当前分页最小为第“1”页',
            'type.in'       => '类型错误：2表示为销售单、6表示换货单！',
            'goods_id.required' => '参数`goods_id`丢失',
            'goods_id.integer'  => '参数`goods_id`仅能为数字',
        ]);

        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }

        //调用查询接口
        $mainId     = $this->getMainUserId();
        return SellReportService::sellGoodsStatement($mainId,$data);
    }


    /**
     * 采购报表(新)
     */
    public function purchaseStatement(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
            'start_time' => 'date_format:Y-m-d',//开始时间
            'end_time' => 'date_format:Y-m-d',//开始时间
        ], [
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'pageSize.min' => '页面展示数据最小为“1”条',
            'currentPage.required' => '参数`currentPage`丢失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
            'currentPage.min' => '当前分页最小为第“1”页',
        ]);

        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }

        //调用查询接口
        $mainId = 0;
        if ($this->getUserId() == $this->getMainUserId()) {
            //调用查询接口
            $mainId = $this->getMainUserId();
        } else {
            if ($this->isShareStorage()) {
                //调用查询接口
                $mainId = $this->getMainUserId();
            } else {
                $data['user_id'] = $this->getUserId();
            }
        }
        return SellReportService::purchaseStatement($mainId, $data);
    }

    /**
     * 根据物料信息查询采购报表（二级）
     */
    public function twoPurchaseStatement(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'goods_id' => 'required|integer|min:1',//商品id
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
            'start_time' => 'date_format:Y-m-d',//开始时间
            'end_time' => 'date_format:Y-m-d',//开始时间
            'materiel_num_sort' => 'nullable|string|in:asc,ASC,desc,DESC',//采购数量排序，asc升，desc降，默认空
            'materiel_debt_sort' => 'nullable|string|in:asc,ASC,desc,DESC',//采购欠款排序，asc升，desc降，默认空
        ], [
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'pageSize.min' => '页面展示数据最小为“1”条',
            'currentPage.required' => '参数`currentPage`丢失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
            'currentPage.min' => '当前分页最小为第“1”页',
            'goods_id.required' => '参数`goods_id`丢失',
            'goods_id.integer' => '参数`goods_id`仅能为数字',
        ]);

        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }

        //调用查询接口
        $mainId = $this->getMainUserId();
        return SellReportService::purchaseStatement($mainId, $data);
    }


    /**
     * 根据物料名，统计销售报表
     */
    public function sellStatementExport(Request $request)
    {
        $data = $request->all();
        //调用查询接口
        $mainId = $this->getMainUserId();
        $result = SellReportService::sellStatementList($mainId, $data, true);
        //导出excel报表
        ob_end_clean();
        ob_start();
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle("销售报表" . date("（Y-m-d）"));

        //设置样式
        $sheet->getDefaultRowDimension()->setRowHeight(22);//默认行高
        $sheet->getDefaultColumnDimension()->setWidth(30);//默认列宽

        //内容标题
        $sheet->mergeCells("A1:F1");
        $sheet->setCellValue("A1", "销售报表" . date("（Y-m-d）"));
        $sheet->getStyle("A1")->getFont()->setSize(14)->setBold(true);

        //副标题
        $sheet->setCellValue("A2", "销售单（NO）")
            ->setCellValue("B2", "客户名称")
            ->setCellValue("C2", "订单销售价（￥）")
            ->setCellValue("D2", "订单记录成本价（￥）")
            ->setCellValue("E2", "订单实时成本价（￥）")
            ->setCellValue("F2", "销售时间");

        //内容主体
        $pageData = $result['pageData'];
        $lineNum = 3;
        if (!empty($pageData)) {
            foreach ($pageData as $row) {
                $sheet->setCellValue("A{$lineNum}", $row['order_no'])
                    ->setCellValue("B{$lineNum}", $row['customer_name'])
                    ->setCellValue("C{$lineNum}", number_format($row['re_sell_price'], 2) . ' ')
                    ->setCellValue("D{$lineNum}", number_format($row['re_cost_price'], 2) . ' ')
                    ->setCellValue("E{$lineNum}", number_format($row['rt_cost_price'], 2) . ' ')
                    ->setCellValue("F{$lineNum}", $row['out_storage_time']);
                $lineNum++;
            }
        }

        //最后总的统计
        $totalData = $result['totalData'];
        $lineNum++;
        $sheet->setCellValue("E{$lineNum}", "销售总金额：");
        $sheet->setCellValue("F{$lineNum}", "￥" . number_format($totalData['re_total_sell_price'], 2));
        $lineNum++;
        $sheet->setCellValue("E{$lineNum}", "销售总成本：");
        $sheet->setCellValue("F{$lineNum}", "￥" . number_format($totalData['re_total_cost_price'], 2));
        $lineNum++;
        $sheet->setCellValue("E{$lineNum}", "实时销售总成本：");
        $sheet->setCellValue("F{$lineNum}", "￥" . number_format($totalData['rt_total_cost_price'], 2));
        $lineNum++;
        $sheet->setCellValue("E{$lineNum}", "实时总利润：");
        $sheet->setCellValue("F{$lineNum}", "￥" . number_format($totalData['rt_total_profit'], 2));
        $lineNum++;
        $sheet->setCellValue("E{$lineNum}", "记录总利润：");
        $sheet->setCellValue("F{$lineNum}", "￥" . number_format($totalData['re_total_profit'], 2));

        //水平，垂直居中
        $sheet->getStyle("A1:E{$lineNum}")->getAlignment()->setHorizontal(Alignment::VERTICAL_CENTER);//垂直
        $sheet->getStyle("A1:F{$lineNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);//水平

        //导出xlsx
        $excelName = "销售报表_" . date("Y_m_d") . '.xlsx';

        //本地调试，线上可以关闭
        $objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $objWriter->save($excelName);
        unlink($excelName);

        $contentTypeXlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

        header('Content-Type: ' . $contentTypeXlsx . '; charset=utf-8');    //输出文件类型
        header('Content-Disposition: attachment;filename="' . $excelName . '"');    //输出文件名
        header('Cache-Control: max-age=0');    //强制每次请求直接发送给源服务器，而不经过本地缓存版本的校验
        header('Access-Control-Allow-Origin:*');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');

        //清空
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit();
    }
    /**
     * 根据物料名，统计销售报表
     */
    public function materielNameListExport(Request $request)
    {
        $data = $request->all();
        //调用查询接口
        $mainId     = $this->getMainUserId();
        $result     = SellReportService::materielNameList($mainId,$data,true);

        //导出excel报表
        ob_end_clean();
        ob_start();
        $spreadsheet    = new Spreadsheet();
        $sheet          = $spreadsheet->getActiveSheet();
        $sheet->setTitle("销售报表".date("（Y-m-d）"));

        //设置样式
        $sheet->getDefaultRowDimension()->setRowHeight(22);//默认行高
        $sheet->getDefaultColumnDimension()->setWidth(30);//默认列宽

        //内容标题
        $sheet->mergeCells("A1:E1");
        $sheet->setCellValue("A1","销售报表".date("（Y-m-d）"));
        $sheet->getStyle("A1")->getFont()->setSize(14)->setBold(true);

        //副标题
        $sheet->setCellValue("A2","商品名称（编号）")
            ->setCellValue("B2","商品数量")
            ->setCellValue("C2","销售价（￥）")
            ->setCellValue("D2","商品成本（￥）")
            ->setCellValue("E2","销售利润（￥）");

        //内容主体
        $pageData   = $result['pageData'];
        $lineNum    = 3;
        if(!empty($pageData))
        {
            foreach ($pageData as $row)
            {
                $sheet->setCellValue("A{$lineNum}",$row['materiel_name'])
                    ->setCellValue("B{$lineNum}",$row['row_operate_num'])
                    ->setCellValue("C{$lineNum}",number_format($row['selling_price'],2).' ')
                    ->setCellValue("D{$lineNum}",number_format($row['cost'],2).' ')
                    ->setCellValue("E{$lineNum}",number_format($row['row_profit_price'],2).' ');
                $lineNum++;
            }
        }

        //最后总的统计
        $totalData  = $result['totalData'];
        $lineNum++;
        $sheet->setCellValue("D{$lineNum}","销售总金额：");
        $sheet->setCellValue("E{$lineNum}","￥".number_format($totalData['total_sell_price'],2));
        $lineNum++;
        $sheet->setCellValue("D{$lineNum}","销售总成本：");
        $sheet->setCellValue("E{$lineNum}","￥".number_format($totalData['total_cost_price'],2));

        //水平，垂直居中
        $sheet->getStyle("A1:E{$lineNum}")->getAlignment()->setHorizontal(Alignment::VERTICAL_CENTER);//垂直
        $sheet->getStyle("A1:E{$lineNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);//水平

        //导出xlsx
        $excelName  = "销售报表_".date("Y_m_d").'.xlsx';

        //本地调试，线上可以关闭
        $objWriter       = IOFactory::createWriter($spreadsheet,'Xlsx');
        $objWriter->save($excelName);
        unlink($excelName);

        $contentTypeXlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

        header('Content-Type: '.$contentTypeXlsx.'; charset=utf-8');    //输出文件类型
        header('Content-Disposition: attachment;filename="'.$excelName.'"');    //输出文件名
        header('Cache-Control: max-age=0');    //强制每次请求直接发送给源服务器，而不经过本地缓存版本的校验
        header('Access-Control-Allow-Origin:*');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');

        //清空
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit();
    }
    /**
     * 根据物料信息二级销售报表导出
     */
    public function sellGoodsStatementExport(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'goods_id'      => 'required|integer|min:1',//商品id
            'start_time'    => 'date_format:Y-m-d',//开始时间
            'end_time'      => 'date_format:Y-m-d',//开始时间
            'sell_num_sort'   => 'nullable|string|in:asc,ASC,desc,DESC',//销售数量排序，asc升，desc降，默认空
            'sell_debt_sort'   => 'nullable|string|in:asc,ASC,desc,DESC',//销售数量排序，asc升，desc降，默认空
            'type' => [
                'required',
                Rule::In([2, 6]),
            ],//条码类型0:商品;1:套餐;
        ],[
            'type.in'       => '类型错误：2表示为销售单、6表示换货单！',
            'goods_id.required' => '参数`goods_id`丢失',
            'goods_id.integer'  => '参数`goods_id`仅能为数字',
        ]);

        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }

        //调用查询接口
        $mainId     = $this->getMainUserId();
        $result     = SellReportService::sellGoodsStatement($mainId,$data,true);

        //导出excel报表
        ob_end_clean();
        ob_start();
        $title = $data['type'] ==2?'销售':'换货';
        $spreadsheet    = new Spreadsheet();
        $sheet          = $spreadsheet->getActiveSheet();
        $sheet->setTitle($title."报表(二级)".date("（Y-m-d）"));

        //设置样式
        $sheet->getDefaultRowDimension()->setRowHeight(22);//默认行高
        $sheet->getDefaultColumnDimension()->setWidth(30);//默认列宽

        //内容标题
        $sheet->mergeCells("A1:G1");
        $sheet->setCellValue("A1",$title."报表(二级)".date("（Y-m-d）"));
        $sheet->getStyle("A1")->getFont()->setSize(14)->setBold(true);

        //副标题
        $sheet->setCellValue("A2","订单编号")
            ->setCellValue("B2","客户名称")
            ->setCellValue("C2","出库数量")
            ->setCellValue("D2","销售价（￥）")
            ->setCellValue("E2","商品成本（￥）")
            ->setCellValue("F2","欠款（￥）")
            ->setCellValue("G2",$title."时间");

        //内容主体
        $pageData   = $result['pageData'];
        $lineNum    = 3;
        if(!empty($pageData))
        {
            foreach ($pageData as $row)
            {
                $sheet->setCellValue("A{$lineNum}",$row['order_no'])
                    ->setCellValue("B{$lineNum}",$row['customer_name'])
                    ->setCellValue("C{$lineNum}",$row['operate_num'])
                    ->setCellValue("D{$lineNum}",number_format($row['materiel_mean_cost'],2).' ')
                    ->setCellValue("E{$lineNum}",number_format($row['sell_price'],2).' ')
                    ->setCellValue("F{$lineNum}",number_format($row['debt'],2).' ')
                    ->setCellValue("G{$lineNum}",$row['out_storage_time']);
                $lineNum++;
            }
        }

        //水平，垂直居中
        $sheet->getStyle("A1:G{$lineNum}")->getAlignment()->setHorizontal(Alignment::VERTICAL_CENTER);//垂直
        $sheet->getStyle("A1:G{$lineNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);//水平

        //导出xlsx
        $excelName  = $title."报表(二级)_".date("Y_m_d").'.xlsx';

        $contentTypeXlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

        header('Content-Type: '.$contentTypeXlsx.'; charset=utf-8');    //输出文件类型
        header('Content-Disposition: attachment;filename="'.$excelName.'"');    //输出文件名
        header('Cache-Control: max-age=0');    //强制每次请求直接发送给源服务器，而不经过本地缓存版本的校验
        header('Access-Control-Allow-Origin:*');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        //清空
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit();
    }

    /**
     * 根据物料信息二级销售报表导出
     */
    public function sellGoodsStatementListExport(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'sell_id' => 'required|integer|min:1',//商品id
        ], [
            'sell_id.required' => '参数`sell_id`丢失',
            'sell_id.integer' => '参数`sell_id`仅能为数字',
        ]);

        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }
        //调用查询接口
        $mainId = $this->getMainUserId();
        $result = SellReportService::sellGoodsStatementList($mainId, $data, true);
        //导出excel报表
        ob_end_clean();
        ob_start();
        $data['type'] = 2;
        $title = $data['type'] == 2 ? '销售' : '换货';
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle($title . "报表(二级)" . date("（Y-m-d）"));

        //设置样式
        $sheet->getDefaultRowDimension()->setRowHeight(22);//默认行高
        $sheet->getDefaultColumnDimension()->setWidth(30);//默认列宽

        //内容标题
        $sheet->mergeCells("A1:D1");
        $sheet->setCellValue("A1", $title . "报表(二级)" . date("（Y-m-d）"));
        $sheet->getStyle("A1")->getFont()->setSize(14)->setBold(true);

        //副标题
        $sheet->setCellValue("A2", "商品名称/规格（编辑）")
            ->setCellValue("B2", "出库数量")
            ->setCellValue("C2", "实时成本价")
            ->setCellValue("D2", "记录成本价");

        //内容主体
        $pageData = $result['pageData'];
        $lineNum = 3;
        if (!empty($pageData)) {
            foreach ($pageData as $row) {
                $sheet->setCellValue("A{$lineNum}", $row['materiel_name'].'/'.
                    $row['type_name'].'（'.$row['materiel_no'].'）')
                    ->setCellValue("B{$lineNum}", $row['num'])
                    ->setCellValue("C{$lineNum}", number_format($row['rt_cost'], 2) . ' ')
                    ->setCellValue("D{$lineNum}", number_format($row['re_cost'], 2) . ' ');
                $lineNum++;
            }
        }
        //最后总的统计
        $totalData = $result['totalData'];
        $lineNum++;
        $sheet->setCellValue("C{$lineNum}", "实时总成本价：");
        $sheet->setCellValue("D{$lineNum}", "￥" . number_format($totalData['rt_total_cost_price'], 2));
        $lineNum++;
        $sheet->setCellValue("C{$lineNum}", "记得总成本价：");
        $sheet->setCellValue("D{$lineNum}", "￥" . number_format($totalData['re_total_cost_price'], 2));
        $lineNum++;
        //水平，垂直居中
        $sheet->getStyle("A1:D{$lineNum}")->getAlignment()->setHorizontal(Alignment::VERTICAL_CENTER);//垂直
        $sheet->getStyle("A1:D{$lineNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);//水平

        //导出xlsx
        $excelName = $title . "报表(二级)_" . date("Y_m_d") . '.xlsx';

        $contentTypeXlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

        header('Content-Type: ' . $contentTypeXlsx . '; charset=utf-8');    //输出文件类型
        header('Content-Disposition: attachment;filename="' . $excelName . '"');    //输出文件名
        header('Cache-Control: max-age=0');    //强制每次请求直接发送给源服务器，而不经过本地缓存版本的校验
        header('Access-Control-Allow-Origin:*');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        //清空
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit();
    }

    /**
     * 采购报表导出（新）
     */
    public function purchaseStatementExport(Request $request)
    {
        $data = $request->all();
        //调用查询接口
        $mainId = $this->getMainUserId();
        $result = SellReportService::purchaseStatement($mainId, $data, true);

        //导出excel报表
        ob_end_clean();
        ob_start();
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle("采购报表" . date("（Y-m-d）"));

        //设置样式
        $sheet->getDefaultRowDimension()->setRowHeight(22);//默认行高
        $sheet->getDefaultColumnDimension()->setWidth(30);//默认列宽

        //内容标题
        $sheet->mergeCells("A1:C1");
        $sheet->setCellValue("A1", "采购报表" . date("（Y-m-d）"));
        $sheet->getStyle("A1")->getFont()->setSize(14)->setBold(true);

        //副标题
        $sheet->setCellValue("A2", "商品名称（编号）")
            ->setCellValue("B2", "商品数量")
            ->setCellValue("C2", "商品成本（￥）");

        //内容主体
        $pageData = $result['pageData'];
        $lineNum = 3;
        if (!empty($pageData)) {
            foreach ($pageData as $row) {
                $sheet->setCellValue("A{$lineNum}", $row['materiel_name'])
                    ->setCellValue("B{$lineNum}", $row['purchase_num'])
                    ->setCellValue("C{$lineNum}", number_format($row['cost'], 2) . ' ');
                $lineNum++;
            }
        }

        //最后总的统计
        $totalData = $result['totalData'];
        $lineNum++;
        $sheet->setCellValue("B{$lineNum}", "采购总金额：");
        $sheet->setCellValue("C{$lineNum}", "￥" . number_format($totalData['purchase_total_price'], 2));

        //水平，垂直居中
        $sheet->getStyle("A1:E{$lineNum}")->getAlignment()->setHorizontal(Alignment::VERTICAL_CENTER);//垂直
        $sheet->getStyle("A1:E{$lineNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);//水平

        //导出xlsx
        $excelName = "采购报表_" . date("Y_m_d") . '.xlsx';

        //本地调试，线上可以关闭
       /* $objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $objWriter->save($excelName);
        unlink($excelName);*/

        $contentTypeXlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

        header('Content-Type: ' . $contentTypeXlsx . '; charset=utf-8');    //输出文件类型
        header('Content-Disposition: attachment;filename="' . $excelName . '"');    //输出文件名
        header('Cache-Control: max-age=0');    //强制每次请求直接发送给源服务器，而不经过本地缓存版本的校验
        header('Access-Control-Allow-Origin:*');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');

        //清空
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit();
    }

    /**
     * 根据物料信息二级销售报表导出
     */
    public function twoPurchaseStatementExport(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'goods_id' => 'required|integer|min:1',//商品id
            'start_time' => 'date_format:Y-m-d',//开始时间
            'end_time' => 'date_format:Y-m-d',//开始时间
            'materiel_num_sort' => 'nullable|string|in:asc,ASC,desc,DESC',//采购数量排序，asc升，desc降，默认空
            'materiel_debt_sort' => 'nullable|string|in:asc,ASC,desc,DESC',//采购欠款排序，asc升，desc降，默认空
        ], [
            'goods_id.required' => '参数`goods_id`丢失',
            'goods_id.integer' => '参数`goods_id`仅能为数字',
        ]);

        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }

        //调用查询接口
        $mainId = $this->getMainUserId();
        $result = SellReportService::purchaseStatement($mainId, $data, true);

        //导出excel报表
        ob_end_clean();
        ob_start();
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle("采购报表(二级)" . date("（Y-m-d）"));

        //设置样式
        $sheet->getDefaultRowDimension()->setRowHeight(22);//默认行高
        $sheet->getDefaultColumnDimension()->setWidth(30);//默认列宽

        //内容标题
        $sheet->mergeCells("A1:F1");
        $sheet->setCellValue("A1", "采购报表(二级)" . date("（Y-m-d）"));
        $sheet->getStyle("A1")->getFont()->setSize(14)->setBold(true);

        //副标题
        $sheet->setCellValue("A2", "订单编号")
            ->setCellValue("B2", "客户名称")
            ->setCellValue("C2", "入库数量")
            ->setCellValue("D2", "商品成本（￥）")
            ->setCellValue("E2", "欠款（￥）")
            ->setCellValue("F2", "采购时间");

        //内容主体
        $pageData = $result['pageData'];
        $lineNum = 3;
        if (!empty($pageData)) {
            foreach ($pageData as $row) {
                $sheet->setCellValue("A{$lineNum}", $row['order_no'])
                    ->setCellValue("B{$lineNum}", $row['customer_name'])
                    ->setCellValue("C{$lineNum}", $row['purchase_num'])
                    ->setCellValue("D{$lineNum}", number_format($row['materiel_mean_cost'], 2) . ' ')
                    ->setCellValue("E{$lineNum}", number_format($row['debt'], 2) . ' ')
                    ->setCellValue("F{$lineNum}", $row['purchase_time']);
                $lineNum++;
            }
        }
        //水平，垂直居中
        $sheet->getStyle("A1:F{$lineNum}")->getAlignment()->setHorizontal(Alignment::VERTICAL_CENTER);//垂直
        $sheet->getStyle("A1:F{$lineNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);//水平

        //导出xlsx
        $excelName = "采购报表(二级)_" . date("Y_m_d") . '.xlsx';

        //本地调试，线上可以关闭
        $objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $objWriter->save($excelName);
        unlink($excelName);

        $contentTypeXlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

        header('Content-Type: ' . $contentTypeXlsx . '; charset=utf-8');    //输出文件类型
        header('Content-Disposition: attachment;filename="' . $excelName . '"');    //输出文件名
        header('Cache-Control: max-age=0');    //强制每次请求直接发送给源服务器，而不经过本地缓存版本的校验
        header('Access-Control-Allow-Origin:*');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        //清空
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit();
    }


    /**
     *设置订单欠款提醒时间
     * Author: zlf
     * Created at 2024/2/22 11:22
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDebtReminderTime(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer|min:1',//订单id
            'debt_reminder_time' => 'required|date',//开始时间
            'type' => [
                'required',
                Rule::In([1, 2, 3]),
            ],//订单类型1:销售;2:换货;3:采购;
        ], [
            'debt_reminder_time.required' => '欠款提醒时间，不能为空！',
            'debt_reminder_time.date_format' => '欠款提醒时间格式有误：(如 2024-2-22 11:11:11)',
            'type.in' => '订单类型错误：1表示为销售单、2表示换货单,3表示采购单！',
            'id.required' => '参数`id`丢失',
            'id.integer' => '参数`id`仅能为数字',
        ]);

        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }
        $data['main_id'] = $this->getMainUserId();
        return response()->json(SellReportService::setDebtReminderTime($data));
    }


    public function sellStatementList(Request $request)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($data = $request->all(), [
            'start_time' => 'date_format:Y-m-d',//开始时间
            'end_time' => 'date_format:Y-m-d',//结束时间
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
        ], [
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'pageSize.min' => '页面展示数据最小为“1”条',
            'currentPage.required' => '参数`currentPage`丢失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
            'currentPage.min' => '当前分页最小为第“1”页',
            'start_time.date_format' => '开始时间格式错误，如：2024-09-09',//开始时间
            'end_time.date_format' => '结束时间格式错误，如：2024-09-10',//结束时间
        ]);
        //验证报告
        if ($valErr = $validator->errors()->first()) {
            return CommonService::fail($valErr);
        }
        $mainId = 0;
        if ($this->getUserId() === $this->getMainUserId()) {
            //调用查询接口
            $mainId = $this->getMainUserId();
        } else {
            if ($this->isShareStorage()) {
                //调用查询接口
                $mainId = $this->getMainUserId();
            } else {
                $data['user_id'] = $this->getUserId();
            }
        }
        return SellReportService::sellStatementList($mainId, $data);
    }
}
